<?php

namespace app\models;

use Yii;
use yii\behaviors\AttributeBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "voice".
 *
 * @property int $id
 * @property string $phone 接收号码
 * @property string $content 发送内容
 * @property string $file 转换成的语音文件
 * @property int $spd 语速
 * @property int $pit 音调
 * @property int $vol 音量
 * @property int $per 发音人:0为普通女声，1为普通男生，3为情感合成-度逍遥，4为情感合成-度丫丫，默认为普通女声
 * @property int $user_id 发送人ID
 * @property int $created_at
 * @property int $updated_at
 */
class Voice extends \yii\db\ActiveRecord
{
    public $per_arr = [
        0 => '普通女声',
        1 => '普通男生',
        3 => '度逍遥（情感合成）',
        4 => '度丫丫（情感合成）',
    ];
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%voice}}';
    }

    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
            [
                'class' => AttributeBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => 'user_id'
                ],
                'value' => function($event){
                    return Yii::$app->user->identity->id;
                }
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['phone', 'content','trunk_name'], 'required'],
            ['phone','validatePhone'],
            [['content'], 'string'],
            [['spd', 'pit', 'vol', 'per'], 'integer'],
            [['file'],'safe'],
        ];
    }

    public function validatePhone()
    {
        if (!$this->hasErrors()){
            foreach (explode(',',$this->phone) as $phone){
                if (!preg_match('/^1[3-9]\d{9}$/',$phone)){
                    $this->addError('phone','手机号码【'.$phone.'】格式有误');
                    return false;
                }
            }
        }
    }

    public function getUser(){
        return $this->hasOne(User::className(),['id'=>'user_id']);
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'phone' => '接收号码',
            'content' => '内容',
            'trunk_name' => '中继线路',
            'spd' => '语速',
            'pit' => '音调',
            'vol' => '音量',
            'per' => '发音人',
        ];
    }

    public function send()
    {
        if ($this->validate()){
            //合成语音文件配置
            $baidu_tts = Yii::$app->params['baidu_tts'];
            $sounds_path = Yii::$app->params['asterisk']['sounds'];
            if (!is_dir($sounds_path."baiduTTS")){
                mkdir($sounds_path."baiduTTS");
            }
            // 初始化AipSpeech对象
            $aipSpeech = new \AipSpeech($baidu_tts['id'], $baidu_tts['key'], $baidu_tts['secret']);
            $fileName = "baiduTTS/" . date('Y-m-d_H-i-s') . '_' . uniqid();
            $result = $aipSpeech->synthesis($this->content, 'zh', 1, [
                'spd' => $this->spd,
                'pit' => $this->pit,
                'vol' => $this->vol,
            ]);
            // 识别正确返回语音二进制 错误则返回json 参照下面错误码
            if (!is_array($result)) {
                $num = file_put_contents($sounds_path.$fileName . ".mp3", $result);
                if ($num > 0) {
                    //批量呼叫
                    $ami = new \AGI_AsteriskManager();
                    $ami->connect();
                    foreach (explode(',',$this->phone) as $phone){
                        $orignate = [
                            'Channel' => 'sip/' . $this->trunk_name .'/'. $phone,
                            'Exten' => $this->trunk_name,
                            'Context' => 'from-internal',
                            'Priority' => '1',
                            'Application' => 'Playback',
                            'Data' => $fileName,
                            'CallerID' => $this->trunk_name,
                            'Async' => true
                        ];
                        $rs = $ami->send_request('Originate', $orignate);
                    }
                    //保存入库
                    $this->file = $sounds_path.$fileName.".mp3";
                    $this->save(false);
                    return true;
                }
            }
            Yii::$app->session->setFlash('info','语音合成失败');
            return false;
        }
        return false;
    }



}
